<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>只有插入功能</title>
    <style>
        #container{
            width: 500px;
            height: 500px;
            border: 1px solid #393939;
        }
    </style>
</head>
<body>
    <div contenteditable="true" id="container"></div>
    <script>
        let spacers = ''
        let anchor = 0
        window.onload = () => {
            const viewContent = document.getElementById('container')
            viewContent.addEventListener('beforeinput', (e) => {
                const inputType = e.inputType
                // 组阻止默认行为
                e.preventDefault(); 
                if (inputType === 'insertText') {
                    const text = e.data
                    const oldSpacers = spacers
                    if (text) {
                        
                        // 更新：spacers
                        spacers = oldSpacers.slice(0, anchor) + text + oldSpacers.slice(anchor)
                        
                        // 更新光标的位置
                        anchor += text.length
                        
                        // 更新视图
                        viewContent.innerHTML = spacers
                        
                        // 更新光标的位置
                        const domSelection = window.getSelection()
                        if (domSelection) {
                            console.log(domSelection)
                            const range = window.document.createRange()
                            range.setStart(viewContent.childNodes[0], anchor)
                            range.setEnd(viewContent.childNodes[0], anchor)
                            domSelection.removeAllRanges()
                            domSelection.addRange(range)
                        }

                    }
                }
            })
        }
    </script>
</body>
</html>